<template>
  <div>
    <!-- 悬浮按钮 -->
    <div 
      class="ai-floating-button"
      @mouseenter="handleFloatingButtonHover"
      v-if="!visible"
    >
      智能助手
    </div>

    <a-drawer
      :visible="visible"
      :width="drawerWidth"
      placement="left"
      @close="close"
      :closable="false"
      class="kiki-ai-drawer"
      :mask="false"
    >
      <!-- 自定义标签栏 -->
      <div class="kiki-tabs-header">
        <div 
          v-for="tab in tabs" 
          :key="tab.key" 
          :class="['kiki-tab-item', { active: currentTab === tab.key }]"
          @click="currentTab = tab.key"
        >
          {{ tab.title }}
        </div>
      </div>
      <!-- 智能SOP内容 -->
      <div v-if="currentTab === 'sop'" class="kiki-tab-content kiki-sop-content">
        <!-- <div class="kiki-sop-header">
          <h3>智能SOP对话</h3>
        </div> -->
        <div class="kiki-sop-main">
          <div v-if="isLoadingSop" class="kiki-loading">
            <a-spin />
            <p>加载SOP数据中...</p>
          </div>
          <div v-else-if="sopError" class="kiki-empty-state">
            <a-empty :description="sopError">
              <a-button type="primary" @click="reloadSopTree">重新加载</a-button>
            </a-empty>
          </div>
          <div v-else class="kiki-sop-messages" ref="sopMessagesRef">
            <template v-if="displayedSopMessages.length">
              <div
                v-for="(message, index) in displayedSopMessages"
                :key="index"
                :class="['message', message.role]"
              >
                <div class="message-body">
                  <div v-if="message.role !== 'system'" class="message-info">
                    <span class="message-sender">{{ message.role === 'user' ? '您' : 'AI助手' }}</span>
                    <span class="message-time">{{ message.time }}</span>
                  </div>
                  <div class="message-content" v-html="renderMarkdown(message.content)"></div>
                  <div class="message-actions">
                    <a-button
                      type="text"
                      size="small"
                      class="copy-btn"
                      @click="copyMessageContent(message.content)"
                    >
                      复制
                    </a-button>
                  </div>
                </div>
              </div>
            </template>
            <div v-else class="empty-chat">
              <div class="empty-chat-content">
                <p>选择一个SOP节点并开始对话</p>
              </div>
            </div>
            <div v-if="hasMoreMessages && !isLoadingMoreMessages" class="load-more-container">
              <a-button type="link" @click="loadMoreMessages">加载更多消息</a-button>
            </div>
            <div v-if="isLoadingMoreMessages" class="loading-more-container">
              <a-spin size="small" />
              <span>加载更多消息中...</span>
            </div>
          </div>
        </div>

        <div class="kiki-sop-footer">
          <div v-if="isGenerating" class="loading-message">
            <span><a-spin /> AI正在思考中...</span>
            <a-button type="link" danger class="cancel-btn" @click="cancelRequest">
              <StopOutlined />
            </a-button>
          </div>
          <a-cascader
            v-model:value="selectedSopPath"
            :options="sopTree"
            :field-names="{ label: 'name', value: 'id' }"
            @change="handleSopNodeChange"
            placeholder="请选择SOP节点"
            :show-checked-strategy="Cascader.SHOW_CHILD"
            :show-search="{ filter }"
            expand-trigger="hover"
            style="width: 100%; margin-bottom: 16px;"
          />
          <a-textarea
            v-model:value="sopContent"
            :rows="3"
            placeholder="请输入您的问题"
            class="kiki-textarea"
            @keydown="handleKeyDown"
          />
          <div class="input-actions">
            <div class="left-actions">
              <a-button type="link" size="small" @click="manualScrollToBottom">
                <template #icon><DownOutlined /></template>
                滚动到底部
              </a-button>
              <a-button type="link" size="small" @click="handleRefreshClick">
                <template #icon><ReloadOutlined /></template>
                刷新
              </a-button>
            </div>
            <a-button
              type="primary"
              :loading="isGenerating"
              @click="sendSopMessage"
            >
              发送
            </a-button>
          </div>
        </div>
      </div>
      <!-- AI助手内容 -->
      <div v-if="currentTab === 'ai'" class="kiki-tab-content kiki-ai-content">
        <div v-if="isLoadingPrompts" class="kiki-loading">
          <a-spin />
          <p>加载提示词中...</p>
        </div>
        <div v-else-if="aiPrompts.length === 0" class="kiki-empty-state">
          <a-empty description="暂无可用提示词">
            <a-button type="primary" @click="loadPrompts">重新加载</a-button>
          </a-empty>
        </div>
        <template v-else>
          <div class="kiki-ai-prompts-container">
            <a-space wrap>
              <a-button
                v-for="prompt in aiPrompts"
                :key="prompt.id || prompt.title"
                @click="selectPrompt(prompt)"
                size="small"
              >
                {{ prompt.title || prompt.name }}
              </a-button>
            </a-space>
          </div>
          
          <div class="kiki-ai-input">
            <a-textarea
              v-model:value="aiPrompt"
              :rows="3"
              placeholder="选择或输入AI提示词"
              class="kiki-textarea"
            />
            <a-button
              type="primary"
              :loading="isGenerating"
              :disabled="!aiPrompt"
              @click="generateAIResponse"
              block
            >
              {{ isGenerating ? '生成中...' : '生成回复' }}
            </a-button>
          </div>
          
          <div class="kiki-ai-response-container">
            <div v-if="isGenerating" class="kiki-loading">
              <a-spin />
              <p>生成回复中...</p>
            </div>
            <div v-else class="kiki-ai-response" v-html="aiResponse" ref="aiResponseRef"></div>
            <div class="kiki-action-buttons">
              <a-space>
                <a-button @click="copyAIResponse" :disabled="!aiResponse">
                  复制
                </a-button>
                <a-button @click="insertAIResponse" :disabled="!aiResponse">
                  插入到聊天
                </a-button>
              </a-space>
            </div>
          </div>
        </template>
      </div>

      <!-- 翻译工具内容 -->
      <div v-if="currentTab === 'translate'" class="kiki-tab-content kiki-translate-content">
        <div class="kiki-translate-input">
          <a-textarea
            v-model:value="sourceText"
            :rows="4"
            placeholder="输入要翻译的文本"
            class="kiki-textarea"
          />
          
          <div class="kiki-translate-controls">
            <a-select
              v-model:value="sourceLang"
              style="width: 120px"
              placeholder="源语言"
            >
              <a-select-option value="auto">自动检测</a-select-option>
              <a-select-option value="zh">中文</a-select-option>
              <a-select-option value="en">英文</a-select-option>
              <a-select-option value="es">西班牙语</a-select-option>
              <a-select-option value="fr">法语</a-select-option>
              <a-select-option value="de">德语</a-select-option>
              <a-select-option value="it">意大利语</a-select-option>
              <a-select-option value="ja">日语</a-select-option>
              <a-select-option value="ko">韩语</a-select-option>
              <a-select-option value="ru">俄语</a-select-option>
            </a-select>
            
            <a-button type="link" @click="switchLanguages">
              <SwapOutlined />
            </a-button>
            
            <a-select
              v-model:value="targetLang"
              style="width: 120px"
              placeholder="目标语言"
            >
              <a-select-option value="zh">中文</a-select-option>
              <a-select-option value="en">英文</a-select-option>
              <a-select-option value="es">西班牙语</a-select-option>
              <a-select-option value="fr">法语</a-select-option>
              <a-select-option value="de">德语</a-select-option>
              <a-select-option value="it">意大利语</a-select-option>
              <a-select-option value="ja">日语</a-select-option>
              <a-select-option value="ko">韩语</a-select-option>
              <a-select-option value="ru">俄语</a-select-option>
            </a-select>
          </div>
          
          <a-button
            type="primary"
            :loading="isTranslating"
            :disabled="!sourceText"
            @click="translate"
            block
          >
            {{ isTranslating ? '翻译中...' : '翻译' }}
          </a-button>
        </div>
        
        <div class="kiki-translate-result">
          <a-textarea
            v-model:value="translatedText"
            :rows="4"
            placeholder="翻译结果"
            readonly
            class="kiki-textarea"
          />
          
          <div class="kiki-action-buttons">
            <a-space>
              <a-button @click="copyTranslation" :disabled="!translatedText">
                复制
              </a-button>
              <a-button @click="insertTranslation" :disabled="!translatedText">
                插入到聊天
              </a-button>
            </a-space>
          </div>
        </div>
      </div>

      <a-button class="kiki-close-button" type="link" @click="close">
        <CloseOutlined />
      </a-button>

      <!-- 拖动调整宽度的手柄 -->
      <div class="resize-handle" @mousedown="startResize"></div>

      <!-- 图片放大组件 -->
      <a-modal 
        v-model:open="imageModalVisible" 
        :footer="null" 
        :closable="true"
        :centered="true"
        :width="imageModalWidth"
        :destroyOnClose="true"
        class="image-preview-modal"
      >
        <a-image
          :src="currentPreviewImage"
          :preview="false"
          class="preview-image"
          v-if="currentPreviewImage"
          :width="'100%'"
        />
      </a-modal>
    </a-drawer>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch, onMounted, nextTick, onUnmounted } from 'vue';
import { translateText, getAuthInfo, fetchAndStoreErpPrompts, generateAIReply, getAISopTree, streamAIChat, generateCustomAIReply } from '../utils/erpapi';
import { STORAGE_KEYS } from '../utils/defines';
import { getCurrentChatId, getCurrentChatNickname } from '../utils/domtools';
import { CloseOutlined, ReloadOutlined, SwapOutlined, StopOutlined, DownOutlined } from '@ant-design/icons-vue';
import MarkdownIt from 'markdown-it';
import SvgIcon from './SvgIcon.vue';
import {
  Drawer,
  Tabs,
  Button,
  Select,
  Textarea,
  Space,
  Spin,
  Empty,
  Cascader,
  message,
  Image,
  Modal
} from 'ant-design-vue';
import type { CascaderProps } from 'ant-design-vue';

// 初始化markdown解析器
const md = new MarkdownIt({
  html: true,
  breaks: true,
  linkify: true,
  typographer: true
});

// 定义SOP节点接口
interface SopNode {
  id: number;
  name: string;
  sop_name: string;
  color?: string;
  parent_id: number | null;
  placeholder: string;
  position: number;
  children?: SopNode[];
}

// 在STORAGE_KEYS常量中可能需要添加新的键，但这里我们直接使用一个常量
const SOP_SELECTED_NODE_KEY = 'KIKI_SELECTED_SOP_NODE';
const DEFAULT_SOP_NODE_ID = 1797;

export default defineComponent({
  name: 'AiDrawer',
  components: {
    'a-drawer': Drawer,
    'a-tabs': Tabs,
    'a-tab-pane': Tabs.TabPane,
    'a-button': Button,
    'a-select': Select,
    'a-select-option': Select.Option,
    'a-textarea': Textarea,
    'a-space': Space,
    'a-spin': Spin,
    'a-empty': Empty,
    'a-cascader': Cascader,
    'a-modal': Modal,
    'a-image': Image,
    CloseOutlined,
    ReloadOutlined,
    SwapOutlined,
    StopOutlined,
    DownOutlined,
    SvgIcon
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    selectedText: {
      type: String,
      default: ''
    }
  },
  emits: ['update:visible', 'close'],
  setup(props, { emit }) {
    const currentTab = ref('sop');
    const sourceText = ref('');
    const translatedText = ref('');
    const isTranslating = ref(false);
    const sourceLang = ref('auto');
    const targetLang = ref('zh');
    
    // 抽屉宽度相关
    const drawerWidth = ref(650);
    const minDrawerWidth = 320;
    const maxDrawerWidth = 900;
    const isResizing = ref(false);
    
    // 图片预览相关
    const imageModalVisible = ref(false);
    const currentPreviewImage = ref('');
    const imageModalWidth = ref('80%');
    
    // 添加悬浮按钮处理函数
    const handleFloatingButtonHover = () => {
      emit('update:visible', true);
    };
    
    // 添加tabs数据
    const tabs = [
      { key: 'sop', title: '智能SOP' },
      { key: 'ai', title: 'AI助手' },
      { key: 'translate', title: '翻译工具' }
    ];
    
    // AI助手相关状态
    const aiPrompt = ref('');
    const aiResponse = ref('');
    const isGenerating = ref(false);
    const aiPrompts = ref<any[]>([]);
    const isLoadingPrompts = ref(false);
    const aiResponseRef = ref<HTMLElement | null>(null);

    // SOP相关状态
    const currentSopName = ref('B2B业务');
    const sopTree = ref<SopNode[]>([]);
    const selectedSopPath = ref<number[]>([]);
    const sopContent = ref('');
    const isLoadingSop = ref(false);
    const sopError = ref('');
    const sopMessages = ref<any[]>([]);
    const controller = ref<AbortController | null>(null);
    const sopMessagesRef = ref<HTMLElement | null>(null);
    
    // 监听visible属性变化
    watch(() => props.visible, (newVal) => {
      if (newVal) {
        if (currentTab.value === 'ai' && aiPrompts.value.length === 0) {
          loadPrompts();
        } else if (currentTab.value === 'sop') {
          if (sopTree.value.length === 0) {
            reloadSopTree();
          } else {
            // 即使SOP树已加载，也要确保加载历史消息
            loadSopMessagesFromCache().then(() => {
              // 加载后初始化消息显示
              initSopMessages();
            });
          }
        }
      }
    });

    // 监听selectedText属性变化
    watch(() => props.selectedText, (newVal) => {
      if (newVal) {
        sourceText.value = newVal;
        translate();
      }
    });

    // 监听标签切换
    watch(() => currentTab.value, (newVal) => {
      if (newVal === 'ai' && aiPrompts.value.length === 0) {
        loadPrompts();
      } else if (newVal === 'sop' && sopTree.value.length === 0) {
        reloadSopTree();
      }
    });

    // 监听selectedSopPath变化，保存到存储
    watch(selectedSopPath, (newVal) => {
      if (newVal && newVal.length > 0) {
        // 保存最后选择的节点ID
        chrome.storage.local.set({ [SOP_SELECTED_NODE_KEY]: newVal });
      }
    }, { deep: true });

    // 组件挂载时加载数据
    onMounted(() => {
      if (props.visible) {
        if (currentTab.value === 'ai') {
          loadPrompts();
        } else if (currentTab.value === 'sop') {
          reloadSopTree();
        }
      }
      
      // 添加全局事件委托处理图片点击
      document.addEventListener('click', handleImageClick);
      
      // 确保组件挂载后，添加图片点击事件监听
      nextTick(() => {
        addImageClickHandlers();
      });
    });
    
    // 添加初始化SOP消息显示的逻辑
    const initSopMessages = () => {
      // 如果消息不超过6条，全部显示
      if (sopMessages.value.length <= 6) {
        displayedSopMessages.value = [...sopMessages.value];
        hasMoreMessages.value = false;
      } else {
        // 只显示最新的6条消息
        displayedSopMessages.value = sopMessages.value.slice(-6);
        hasMoreMessages.value = true;
      }
      
      // 初始化后滚动到底部
      nextTick(() => {
        autoScrollToBottom();
      });
    };
    
    // 监听SOP消息变化，更新显示
    watch(sopMessages, () => {
      // 缓存限制: 如果消息超过50条，只保留最新的50条
      if (sopMessages.value.length > 50) {
        sopMessages.value = sopMessages.value.slice(-50);
      }
      
      // 初始化显示消息，显示最近的6条
      if (sopMessages.value.length <= 6) {
        displayedSopMessages.value = [...sopMessages.value];
        hasMoreMessages.value = false;
      } else {
        displayedSopMessages.value = sopMessages.value.slice(-6);
        hasMoreMessages.value = true;
      }
      
      // 保存消息到缓存
      saveSopMessagesToCache();
      
      nextTick(() => {
        addImageClickHandlers();
      });
    }, { deep: true });
    
    // 加载更多消息的方法
    const loadMoreMessages = () => {
      if (!hasMoreMessages.value || isLoadingMoreMessages.value) return;
      
      isLoadingMoreMessages.value = true;
      
      // 模拟加载延迟
      setTimeout(() => {
        const currentLength = displayedSopMessages.value.length;
        const totalLength = sopMessages.value.length;
        
        // 每次多加载10条，或者剩余的全部消息
        const moreToLoad = Math.min(10, totalLength - currentLength);
        
        if (moreToLoad > 0) {
          // 在当前显示的消息前面添加更多消息
          const startIndex = totalLength - currentLength - moreToLoad;
          const messagesToAdd = sopMessages.value.slice(startIndex, startIndex + moreToLoad);
          displayedSopMessages.value = [...messagesToAdd, ...displayedSopMessages.value];
          
          // 检查是否还有更多消息
          hasMoreMessages.value = displayedSopMessages.value.length < totalLength;
        } else {
          hasMoreMessages.value = false;
        }
        
        isLoadingMoreMessages.value = false;
      }, 500);
    };
    
    // 组件卸载时移除事件监听
    onUnmounted(() => {
      document.removeEventListener('click', handleImageClick);
    });

    // 添加图片点击事件处理
    const addImageClickHandlers = () => {
      // 为AI响应区域的图片添加点击事件
      if (aiResponseRef.value) {
        const images = aiResponseRef.value.querySelectorAll('img');
        images.forEach(img => {
          (img as HTMLImageElement).style.cursor = 'pointer';
          img.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            currentPreviewImage.value = (img as HTMLImageElement).src;
            imageModalVisible.value = true;
          });
        });
      }
      
      // 为SOP消息区域的图片添加点击事件
      if (sopMessagesRef.value) {
        const images = sopMessagesRef.value.querySelectorAll('.message-content img');
        images.forEach(img => {
          (img as HTMLImageElement).style.cursor = 'pointer';
          img.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            currentPreviewImage.value = (img as HTMLImageElement).src;
            imageModalVisible.value = true;
          });
        });
      }
    };
    
    // 监听AI响应变化，为新的图片添加点击事件
    watch(aiResponse, () => {
      nextTick(() => {
        addImageClickHandlers();
      });
    });
    
    // 监听SOP消息变化，为新的图片添加点击事件
    watch(sopMessages, () => {
      nextTick(() => {
        addImageClickHandlers();
      });
    }, { deep: true });

    const handleImageClick = (event: MouseEvent) => {
      const target = event.target as HTMLElement;
      if (target.tagName === 'IMG' && 
          (target.closest('.kiki-ai-response') || 
           target.closest('.message-content'))) {
        // 点击的是AI响应或SOP消息中的图片
        event.preventDefault();
        currentPreviewImage.value = (target as HTMLImageElement).src;
        imageModalVisible.value = true;
      }
    };

    // 从存储中加载提示词
    const loadPrompts = async () => {
      if (isLoadingPrompts.value) return;
      
      isLoadingPrompts.value = true;
      try {
        const promptsData = await new Promise<any>((resolve) => {
          chrome.storage.local.get([STORAGE_KEYS.PROMPTS], (result) => {
            resolve(result[STORAGE_KEYS.PROMPTS] || null);
          });
        });

        if (promptsData && Array.isArray(promptsData)) {
          aiPrompts.value = promptsData;
        } else {
          await fetchPromptsFromServer();
        }
      } catch (error) {
        console.error('加载提示词失败:', error);
      } finally {
        isLoadingPrompts.value = false;
      }
    };

    // 从服务器获取提示词
    const fetchPromptsFromServer = async () => {
      try {
        const authInfo = await getAuthInfo();
        if (!authInfo.authorization || !authInfo.ptoken) {
          throw new Error('缺少认证信息');
        }

        const data = await fetchAndStoreErpPrompts(authInfo);
        if (data && Array.isArray(data)) {
          aiPrompts.value = data;
        }
      } catch (error) {
        console.error('从服务器获取提示词失败:', error);
        message.error('获取提示词失败，请稍后重试');
      }
    };

    // AI助手方法
    const selectPrompt = async (prompt: any) => {
      if (!prompt.id) {
        message.error('无效的提示词');
        return;
      }
      
      isGenerating.value = true;
      try {
        const chatId = getCurrentChatId();
        if (!chatId) {
          throw new Error('无法获取聊天ID');
        }
        
        const nickname = getCurrentChatNickname() || '';
        
        const result = await generateAIReply(prompt.id, chatId);
        if (result && result.data) {
          aiResponse.value = result.data;
        } else {
          throw new Error('无效的响应数据');
        }
      } catch (error) {
        console.error('AI生成失败:', error);
        message.error('AI生成失败，请稍后重试');
      } finally {
        isGenerating.value = false;
      }
    };

    const generateAIResponse = async () => {
      if (!aiPrompt.value || isGenerating.value) return;
      
      isGenerating.value = true;
      try {
        const chatId = getCurrentChatId();
        if (!chatId) {
          throw new Error('无法获取聊天ID');
        }
        
        // 使用自定义提示词生成回复
        const result = await generateCustomAIReply(chatId, aiPrompt.value);
        if (result && result.data) {
          aiResponse.value = result.data;
        } else {
          throw new Error('无效的响应数据');
        }
      } catch (error) {
        console.error('AI生成失败:', error);
        message.error('AI生成失败，请稍后重试');
      } finally {
        isGenerating.value = false;
      }
    };

    const copyAIResponse = () => {
      if (!aiResponse.value) return;
      
      const tempDiv = document.createElement('div');
      tempDiv.innerHTML = aiResponse.value;
      const textContent = tempDiv.textContent || tempDiv.innerText || '';
      
      try {
        if (window.ClipboardItem) {
          const clipboardItem = new ClipboardItem({
            'text/html': new Blob([aiResponse.value], { type: 'text/html' }),
            'text/plain': new Blob([textContent], { type: 'text/plain' })
          });
          navigator.clipboard.write([clipboardItem])
            .then(() => {
              message.success('已复制到剪贴板（富文本）');
            })
            .catch(() => fallbackToCopyText());
        } else {
          fallbackToCopyText();
        }
      } catch (e) {
        console.error('复制尝试失败:', e);
        fallbackToCopyText();
      }
      
      function fallbackToCopyText() {
        navigator.clipboard.writeText(textContent)
          .then(() => {
            message.success('已复制到剪贴板（纯文本）');
          })
          .catch(() => {
            message.error('复制失败，请手动复制');
          });
      }
    };

    const insertAIResponse = async () => {
      if (!aiResponse.value) return;
      
      const tempDiv = document.createElement('div');
      tempDiv.innerHTML = aiResponse.value;
      const textContent = tempDiv.textContent || tempDiv.innerText || '';
      
      const success = await setEditorContent2(textContent);
      if (!success) {
        message.error('插入内容失败');
      }
    };

    // 翻译文本
    const translate = async () => {
      if (!sourceText.value || isTranslating.value) return;
      
      isTranslating.value = true;
      try {
        const result = await translateText(sourceText.value, targetLang.value);
        if (result) {
          translatedText.value = result;
        } else {
          throw new Error('翻译失败');
        }
      } catch (error) {
        console.error('翻译失败:', error);
        message.error('翻译失败，请稍后重试');
      } finally {
        isTranslating.value = false;
      }
    };
    
    // 切换语言
    const switchLanguages = () => {
      if (sourceLang.value !== 'auto') {
        const temp = sourceLang.value;
        sourceLang.value = targetLang.value;
        targetLang.value = temp;
      }
    };
    
    // 复制翻译结果
    const copyTranslation = () => {
      if (!translatedText.value) return;
      
      navigator.clipboard.writeText(translatedText.value)
        .then(() => {
          message.success('已复制到剪贴板');
        })
        .catch(() => {
          message.error('复制失败，请手动复制');
        });
    };
    
    // 插入翻译结果到聊天
    const insertTranslation = async () => {
      if (!translatedText.value) return;
      
      const success = await setEditorContent2(translatedText.value);
      if (!success) {
        message.error('插入内容失败');
      }
    };
    
    // 关闭抽屉
    const close = () => {
      emit('update:visible', false);
      emit('close');
    };

    // 点击刷新按钮时，强制刷新SOP树
    const handleRefreshClick = () => {
      loadSopTree(true);
    };

    // 重新加载SOP树（不强制刷新）
    const reloadSopTree = () => {
      loadSopTree(false);
    };

    // 加载SOP树形结构数据
    const loadSopTree = async (forceRefresh: boolean = false) => {
      if (isLoadingSop.value) return;
      
      sopError.value = '';
      isLoadingSop.value = true;
      
      try {
        // 首先尝试从缓存加载消息
        await loadSopMessagesFromCache();
        
        // 然后加载SOP树结构
        const response = await getAISopTree(currentSopName.value, forceRefresh);
        
        // 重置树和路径选择
        sopTree.value = [];
        selectedSopPath.value = [];
        sopContent.value = '';
        
        if (response && Array.isArray(response)) {
          // 处理数据，移除 disabled 属性
          const processNode = (node: any): SopNode => {
            const processedNode: SopNode = {
              id: node.id,
              name: node.name,
              sop_name: node.sop_name,
              color: node.color,
              parent_id: node.parent_id,
              placeholder: node.placeholder,
              position: node.position
            };
            
            if (node.children && node.children.length > 0) {
              processedNode.children = node.children.map(processNode);
            }
            
            return processedNode;
          };
          
          sopTree.value = response.map(processNode);
          
          // 成功加载SOP树后，初始化消息显示
          initSopMessages();
          
          // 恢复上次选择的节点或设置默认节点
          restorePreviouslySelectedNode();
        } else {
          sopError.value = '无效的SOP数据结构';
        }
      } catch (error: any) {
        console.error('加载SOP数据失败:', error);
        sopError.value = error.message || '加载失败';
      } finally {
        isLoadingSop.value = false;
      }
    };
    
    // 恢复上次选择的节点或设置默认节点
    const restorePreviouslySelectedNode = async () => {
      try {
        // 从存储中获取上次选择的节点
        const storedNode = await new Promise<number[]>((resolve) => {
          chrome.storage.local.get([SOP_SELECTED_NODE_KEY], (result) => {
            resolve(result[SOP_SELECTED_NODE_KEY] || []);
          });
        });
        
        if (storedNode && storedNode.length > 0) {
          // 检查存储的节点是否在当前树中
          const nodeExists = checkNodeExistsInTree(storedNode);
          if (nodeExists) {
            selectedSopPath.value = storedNode;
            updatePlaceholderForSelectedNode();
            return;
          }
        }
        
        // 如果没有存储的节点或存储的节点不在当前树中，查找默认节点
        findAndSelectDefaultNode();
      } catch (error) {
        console.error('恢复选择的节点失败:', error);
        // 出错时查找默认节点
        findAndSelectDefaultNode();
      }
    };
    
    // 检查节点是否存在于当前树中的辅助函数
    const checkNodeExistsInTree = (nodePath: number[]): boolean => {
      if (!nodePath || nodePath.length === 0 || !sopTree.value || sopTree.value.length === 0) {
        return false;
      }
      
      let currentNodes = sopTree.value;
      let exists = true;
      
      // 遍历路径中的每个节点ID
      for (let i = 0; i < nodePath.length; i++) {
        const nodeId = nodePath[i];
        const foundNode = currentNodes.find(node => node.id === nodeId);
        
        if (!foundNode) {
          exists = false;
          break;
        }
        
        if (i < nodePath.length - 1) {
          // 如果不是最后一个节点，继续向下查找
          if (!foundNode.children || foundNode.children.length === 0) {
            exists = false;
            break;
          }
          currentNodes = foundNode.children;
        }
      }
      
      return exists;
    };
    
    // 查找并选择默认节点
    const findAndSelectDefaultNode = () => {
      // 在树中查找ID为DEFAULT_SOP_NODE_ID的节点
      const findNodePath = (nodes: SopNode[], targetId: number, currentPath: number[] = []): number[] | null => {
        for (const node of nodes) {
          const newPath = [...currentPath, node.id];
          
          if (node.id === targetId) {
            return newPath;
          }
          
          if (node.children && node.children.length > 0) {
            const foundPath = findNodePath(node.children, targetId, newPath);
            if (foundPath) {
              return foundPath;
            }
          }
        }
        
        return null;
      };
      
      const defaultNodePath = findNodePath(sopTree.value, DEFAULT_SOP_NODE_ID);
      if (defaultNodePath) {
        selectedSopPath.value = defaultNodePath;
        updatePlaceholderForSelectedNode();
      }
    };
    
    // 更新选中节点的placeholder
    const updatePlaceholderForSelectedNode = () => {
      if (!selectedSopPath.value || selectedSopPath.value.length === 0) return;
      
      const getNodeByPath = (nodes: SopNode[], path: number[], index: number = 0): SopNode | null => {
        if (index >= path.length) return null;
        
        const currentNodeId = path[index];
        const currentNode = nodes.find(node => node.id === currentNodeId);
        
        if (!currentNode) return null;
        
        if (index === path.length - 1) {
          return currentNode;
        }
        
        if (!currentNode.children || currentNode.children.length === 0) {
          return null;
        }
        
        return getNodeByPath(currentNode.children, path, index + 1);
      };
      
      const selectedNode = getNodeByPath(sopTree.value, selectedSopPath.value);
      if (selectedNode && selectedNode.placeholder) {
        sopContent.value = selectedNode.placeholder;
      }
    };

    // 从缓存加载SOP消息
    const loadSopMessagesFromCache = async () => {
      try {
        // 从localStorage或chrome.storage加载历史消息
        const cachedMessages = await new Promise<any[]>((resolve) => {
          chrome.storage.local.get([STORAGE_KEYS.SOP_MESSAGES], (result) => {
            resolve(result[STORAGE_KEYS.SOP_MESSAGES] || []);
          });
        });
        
        if (Array.isArray(cachedMessages) && cachedMessages.length > 0) {
          // 限制最多50条历史消息
          sopMessages.value = cachedMessages.slice(-50);
          return true;
        } else {
          sopMessages.value = [];
          return false;
        }
      } catch (error) {
        console.error('加载历史消息失败:', error);
        // 加载失败不影响使用，只是没有历史消息
        sopMessages.value = [];
        return false;
      }
    };
    
    // 保存SOP消息到缓存
    const saveSopMessagesToCache = async () => {
      try {
        // 保存到localStorage或chrome.storage
        await new Promise<void>((resolve) => {
          chrome.storage.local.set({ [STORAGE_KEYS.SOP_MESSAGES]: sopMessages.value }, () => {
            resolve();
          });
        });
      } catch (error) {
        console.error('保存消息失败:', error);
      }
    };
    
    // 处理SOP节点选择变化
    const handleSopNodeChange = (value: any, selectedOptions: any[]) => {
      if (selectedOptions.length > 0) {
        const selectedNode = selectedOptions[selectedOptions.length - 1];
        sopContent.value = selectedNode.placeholder || '';
        
        // 将选择保存到存储中
        chrome.storage.local.set({ [SOP_SELECTED_NODE_KEY]: value });
      }
    };
    
    // 格式化时间
    const formatTime = () => {
      const now = new Date();
      return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
    };

    // 发送SOP消息
    const sendSopMessage = async () => {
      if (!selectedSopPath.value.length || isGenerating.value) return;

      // 添加用户消息
      sopMessages.value.push({
        role: 'user',
        content: sopContent.value || '',
        time: formatTime()
      });

      const userMessage = sopContent.value || '';
      sopContent.value = '';
      
      // 更新显示的消息列表
      if (sopMessages.value.length <= 6) {
        displayedSopMessages.value = [...sopMessages.value];
      } else {
        // 始终显示最新的消息
        displayedSopMessages.value = sopMessages.value.slice(-6);
        hasMoreMessages.value = true;
      }
      
      // 保存消息到缓存
      saveSopMessagesToCache();
      
      // 消息添加后立即滚动到底部
      autoScrollToBottom();

      // 显示加载状态
      isGenerating.value = true;

      // 添加AI回复占位消息
      const assistantMessageIndex = sopMessages.value.length;
      sopMessages.value.push({
        role: 'assistant',
        content: '',
        time: formatTime()
      });
      
      // 更新显示的消息
      if (sopMessages.value.length <= 6) {
        displayedSopMessages.value = [...sopMessages.value];
      } else {
        displayedSopMessages.value = sopMessages.value.slice(-6);
        hasMoreMessages.value = true;
      }
      
      // 保存消息到缓存
      saveSopMessagesToCache();

      try {
        // 创建请求对象
        controller.value = new AbortController();
        const signal = controller.value.signal;

        // 获取当前聊天ID
        const chatId = getCurrentChatId() || '';
        
        // 获取account_serialized
        const accountSerialized = await new Promise<string>((resolve) => {
          chrome.storage.local.get([STORAGE_KEYS.ACCOUNT_ID], (result) => {
            resolve(result[STORAGE_KEYS.ACCOUNT_ID] || '');
          });
        });

        // 使用新的流式接口，传入chat_id和account_serialized
        const response = await streamAIChat(
          selectedSopPath.value[selectedSopPath.value.length - 1],
          userMessage,
          signal,
          chatId,
          accountSerialized
        );

        // 获取响应的可读流
        const reader = response.body?.getReader();
        const decoder = new TextDecoder('utf-8');
        let responseText = '';

        // 处理流式响应
        while (true) {
          const { done, value } = await reader!.read();
          if (done) break;

          // 解码二进制数据
          const chunk = decoder.decode(value, { stream: true });

          // 累加响应文本
          responseText += chunk;

          // 更新AI回复内容
          sopMessages.value[assistantMessageIndex].content = responseText;
          
          // 确保最新消息始终可见
          if (displayedSopMessages.value.length > 0) {
            // 更新最后一条消息的内容
            const lastIndex = displayedSopMessages.value.length - 1;
            if (displayedSopMessages.value[lastIndex].role === 'assistant') {
              displayedSopMessages.value[lastIndex].content = responseText;
            }
          }
          
          // 每次内容更新时自动滚动到底部
          autoScrollToBottom();
        }

        isGenerating.value = false;
        controller.value = null;
        
        // 保存最终消息到缓存
        saveSopMessagesToCache();
      } catch (error: any) {
        console.error('发送消息失败', error);

        // 如果是用户主动取消，不显示错误消息
        if (error.name === 'AbortError') {
          sopMessages.value[assistantMessageIndex].content += '\n\n[用户已取消回复]';
        } else {
          sopMessages.value[assistantMessageIndex].content = '抱歉，发生了错误，请稍后再试。';
        }

        isGenerating.value = false;
        controller.value = null;
        
        // 保存错误消息到缓存
        saveSopMessagesToCache();
      }
    };

    // 取消当前请求
    const cancelRequest = () => {
      if (controller.value) {
        controller.value.abort();
        controller.value = null;
        isGenerating.value = false;
      }
    };

    // 复制消息内容
    const copyMessageContent = (content: string) => {
      navigator.clipboard.writeText(content)
        .then(() => {
          message.success('已复制到剪贴板');
        })
        .catch(() => {
          message.error('复制失败，请手动复制');
        });
    };

    // 过滤搜索函数
    const filter = (inputValue: string, path: any[]) => {
      return path.some(option => (option.name || '').toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
    };

    // 添加 renderMarkdown 函数
    const renderMarkdown = (text: string) => {
      if (!text) return '';
      return md.render(text);
    };

    // 定义setEditorContent2函数
    const setEditorContent2 = async (content: string): Promise<boolean> => {
      try {
        const editorElement = document.querySelector('[contenteditable="true"]');
        if (!editorElement) {
          console.error('未找到编辑器元素');
          return false;
        }
        
        editorElement.textContent = content;
        
        const inputEvent = new Event('input', { bubbles: true });
        editorElement.dispatchEvent(inputEvent);
        
        return true;
      } catch (error) {
        console.error('插入内容失败:', error);
        return false;
      }
    };

    // 手动滚动到底部按钮功能
    const manualScrollToBottom = () => {
      if (sopMessagesRef.value && sopMessagesRef.value.parentElement) {
        sopMessagesRef.value.parentElement.scrollTop = sopMessagesRef.value.parentElement.scrollHeight;
      }
    };

    // 自动滚动到底部函数 - 与手动滚动功能相同，只是自动触发
    const autoScrollToBottom = () => {
      setTimeout(() => {
        if (sopMessagesRef.value && sopMessagesRef.value.parentElement) {
          sopMessagesRef.value.parentElement.scrollTop = sopMessagesRef.value.parentElement.scrollHeight;
        }
      }, 50);
    };

    // 添加拖动调整宽度的逻辑
    const startResize = (e: MouseEvent) => {
      e.preventDefault();
      isResizing.value = true;
      
      // 记录初始位置和宽度
      const initialX = e.clientX;
      const initialWidth = drawerWidth.value;
      
      const onMouseMove = (e: MouseEvent) => {
        if (!isResizing.value) return;
        
        // 计算鼠标移动距离
        const deltaX = e.clientX - initialX;
        
        // 计算新宽度（向右拖动增加宽度，向左拖动减少宽度）
        const newWidth = initialWidth + deltaX;
        
        // 限制最小/最大宽度
        if (newWidth >= minDrawerWidth && newWidth <= maxDrawerWidth) {
          drawerWidth.value = newWidth;
        }
      };
      
      const onMouseUp = () => {
        isResizing.value = false;
        document.removeEventListener('mousemove', onMouseMove);
        document.removeEventListener('mouseup', onMouseUp);
      };
      
      document.addEventListener('mousemove', onMouseMove);
      document.addEventListener('mouseup', onMouseUp);
    };

    // 新增变量
    const displayedSopMessages = ref<any[]>([]);
    const hasMoreMessages = ref(true);
    const isLoadingMoreMessages = ref(false);

    // 处理键盘按键
    const handleKeyDown = (e: KeyboardEvent) => {
      // 如果按下Enter键且没有同时按下Shift键(Shift+Enter用于换行)
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault(); // 阻止默认的换行行为
        if (selectedSopPath.value.length && !isGenerating.value) {
          sendSopMessage();
        }
      }
    };

    return {
      currentTab,
      sourceText,
      translatedText,
      isTranslating,
      sourceLang,
      targetLang,
      aiPrompt,
      aiResponse,
      isGenerating,
      aiPrompts,
      currentSopName,
      sopTree,
      selectedSopPath,
      sopContent,
      isLoadingSop,
      sopError,
      Cascader,
      filter,
      loadSopTree,
      handleSopNodeChange,
      translate,
      switchLanguages,
      copyTranslation,
      insertTranslation,
      close,
      selectPrompt,
      generateAIResponse,
      copyAIResponse,
      insertAIResponse,
      loadPrompts,
      fetchPromptsFromServer,
      isLoadingPrompts,
      sopMessages,
      sopMessagesRef,
      sendSopMessage,
      cancelRequest,
      copyMessageContent,
      renderMarkdown,
      setEditorContent2,
      tabs,
      aiResponseRef,
      manualScrollToBottom,
      imageModalVisible,
      currentPreviewImage,
      imageModalWidth,
      drawerWidth,
      startResize,
      handleRefreshClick,
      reloadSopTree,
      displayedSopMessages,
      hasMoreMessages,
      isLoadingMoreMessages,
      loadMoreMessages,
      handleKeyDown,
      handleFloatingButtonHover,
    };
  }
});
</script>

<style scoped>
.kiki-ai-drawer {
  :deep(.ant-drawer-content-wrapper) {
    transition: width 0.2s ease !important;
  }
  
  :deep(.ant-drawer-content) {
    height: 100%;
    overflow: hidden;
  }
  
  :deep(.ant-drawer-body) {
    padding: 0;
    height: 100%;
    max-height: 100vh;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    position: relative;
  }
}

/* 拖动手柄样式 */
.resize-handle {
  position: absolute;
  right: 0;
  top: 0;
  width: 8px;
  height: 100%;
  cursor: ew-resize;
  background-color: transparent;
  z-index: 100;
}

.resize-handle:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

/* 自定义标签页样式 */
.kiki-tabs-header {
  display: flex;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
  padding: 0 20px;
  height: 46px;
  flex: none;
  z-index: 10;
}

.kiki-tab-item {
  padding: 0 16px;
  height: 46px;
  line-height: 46px;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
  color: #666;
}

.kiki-tab-item.active {
  color: #1890ff;
  font-weight: 500;
}

.kiki-tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: #1890ff;
}

.kiki-tab-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: calc(100% - 46px); /* 使用相对高度 */
  overflow: hidden;
  position: relative;
}

.kiki-close-button {
  position: absolute;
  right: 16px;
  top: 8px;
  z-index: 11;
}

/* 基础组件样式 */
.kiki-textarea {
  margin-bottom: 8px;
  resize: none;
  border-radius: 4px;
}

.kiki-translate-controls {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
}

.kiki-action-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

/* 状态样式 */
.kiki-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 32px;
  gap: 16px;
  height: 100%;
  background: rgba(255, 255, 255, 0.95);
}

.kiki-empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 32px;
  gap: 16px;
  height: 100%;
  background: #fff;
}

/* SOP布局相关 */
.kiki-sop-content {
  position: relative;
  height: 100%;
  overflow: hidden;
}

.kiki-sop-header {
  height: 50px;
  padding: 12px 20px;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
  flex: none;
  display: flex;
  align-items: center;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: 5;
}

.kiki-sop-main {
  position: absolute;
  top: 50px; /* header高度 */
  left: 0;
  right: 0;
  bottom: 200px; /* footer高度 */
  overflow-y: auto;
  background: #f5f7fa;
}

.kiki-sop-messages {
  padding: 20px;
  display: flex;
  flex-direction: column;
  width: 100%;
}

.kiki-sop-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 200px;
  background: #fff;
  border-top: 1px solid #f0f0f0;
  padding: 12px 20px 20px;
  box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.03);
  z-index: 5;
}

/* AI助手相关 */
.kiki-ai-content {
  position: relative;
}

.kiki-ai-prompts-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  max-height: 120px;
  overflow-y: auto;
  padding: 12px 20px;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
}

.kiki-ai-input {
  position: absolute;
  top: 120px;
  left: 0;
  right: 0;
  height: 160px;
  padding: 16px 20px;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
}

.kiki-ai-response-container {
  position: absolute;
  top: 280px; /* 头部高度和输入框高度总和 */
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
  padding: 16px 20px;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.kiki-ai-response {
  height: calc(100% - 60px); /* 减去操作按钮的高度 */
  overflow-y: auto;
  padding: 16px;
  background-color: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

/* 翻译工具相关 */
.kiki-translate-content {
  position: relative;
}

.kiki-translate-input {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 220px;
  padding: 16px 20px;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
}

.kiki-translate-result {
  position: absolute;
  top: 220px;
  left: 0;
  right: 0;
  bottom: 0;
  overflow-y: auto;
  padding: 16px 20px;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
}

/* 富文本内容样式 */
.kiki-ai-response :deep(h1),
.kiki-ai-response :deep(h2),
.kiki-ai-response :deep(h3),
.kiki-ai-response :deep(h4),
.kiki-ai-response :deep(h5),
.kiki-ai-response :deep(h6) {
  margin-top: 16px;
  margin-bottom: 8px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
}

.kiki-ai-response :deep(h1) { font-size: 24px; }
.kiki-ai-response :deep(h2) { font-size: 20px; }
.kiki-ai-response :deep(h3) { font-size: 16px; }
.kiki-ai-response :deep(h4) { font-size: 14px; }
.kiki-ai-response :deep(h5),
.kiki-ai-response :deep(h6) { font-size: 12px; }

.kiki-ai-response :deep(p) {
  margin-bottom: 8px;
}

.kiki-ai-response :deep(ul),
.kiki-ai-response :deep(ol) {
  padding-left: 24px;
  margin-bottom: 8px;
}

.kiki-ai-response :deep(li) {
  margin-bottom: 4px;
}

.kiki-ai-response :deep(a) {
  color: #1890ff;
  text-decoration: none;
}

.kiki-ai-response :deep(code) {
  background-color: #f5f5f5;
  padding: 2px 4px;
  border-radius: 2px;
  font-family: monospace;
  font-size: 12px;
}

.kiki-ai-response :deep(pre) {
  background-color: #f5f5f5;
  padding: 12px;
  border-radius: 4px;
  overflow-x: auto;
  margin-bottom: 8px;
}

.kiki-ai-response :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 8px;
}

.kiki-ai-response :deep(th),
.kiki-ai-response :deep(td) {
  border: 1px solid #f0f0f0;
  padding: 8px;
  text-align: left;
}

.kiki-ai-response :deep(th) {
  background-color: #fafafa;
}

.kiki-ai-response :deep(blockquote) {
  border-left: 3px solid #1890ff;
  padding-left: 12px;
  margin-left: 0;
  color: rgba(0, 0, 0, 0.45);
}

.kiki-ai-response :deep(img) {
  max-width: 100%;
  height: auto;
}

/* 聊天消息样式 */
.message {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
  padding: 12px;
  border-radius: 8px;
  width: 90%;
}

.message.user {
  flex-direction: row;
  background-color: #e3f2ff;
  margin-left: auto;
  margin-right: 0;
}

.message.assistant {
  flex-direction: row;
  background-color: #fff;
  margin-left: 0;
  margin-right: auto;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.message-avatar {
  flex-shrink: 0;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  border: 1px solid #e8e8e8;
}

.message-avatar :deep(svg) {
  width: 20px;
  height: 20px;
}

.message-body {
  flex: 1;
  min-width: 0;
}

.message-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.message-sender {
  font-weight: 500;
  color: #333;
}

.message-time {
  font-size: 12px;
  color: #999;
}

.message-content {
  word-break: break-word;
  line-height: 1.6;
  user-select: text; /* 允许选择文本 */
}

.message-content :deep(img) {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
  margin: 8px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.message-content :deep(p) {
  margin: 8px 0;
}

.message-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 8px;
  opacity: 0;
  transition: opacity 0.2s;
}

.message:hover .message-actions {
  opacity: 1;
}

.empty-chat {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-chat-content {
  text-align: center;
  color: #999;
}

.empty-chat-content :deep(svg) {
  width: 48px;
  height: 48px;
  margin-bottom: 16px;
  color: #d9d9d9;
}

.loading-message {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
  padding: 8px 12px;
  background: #f5f7fa;
  border-radius: 4px;
}

.loading-message span {
  display: flex;
  align-items: center;
  gap: 8px;
}

.cancel-btn {
  padding: 0;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.left-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.input-tip {
  color: #909399;
  font-size: 12px;
}

.scroll-button-container {
  display: flex;
  justify-content: center;
  margin-bottom: 12px;
}

.scroll-button {
  font-size: 12px;
  height: 24px;
  padding: 0 8px;
  border-radius: 12px;
  background: rgba(24, 144, 255, 0.1);
  color: #1890ff;
}

.preview-image {
  width: 100%;
  height: auto;
  object-fit: contain;
}

.image-preview-modal {
  :deep(.ant-modal-content) {
    background-color: rgba(0, 0, 0, 0.85);
    
    .ant-modal-close {
      color: #fff;
    }
    
    .ant-modal-body {
      padding: 24px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}

.load-more-container {
  display: flex;
  justify-content: center;
  margin-bottom: 16px;
  margin-top: 8px;
}

.loading-more-container {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  margin-top: 8px;
  color: #999;
}

/* 悬浮按钮样式 */
.ai-floating-button {
  position: fixed;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  background-color: #4CAF50;
  color: white;
  width: 40px;
  height: 180px;
  border-radius: 0 8px 8px 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-weight: 500;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.15);
  cursor: pointer;
  z-index: 999;
  transition: all 0.3s;
  writing-mode: vertical-lr;
  text-orientation: upright;
  font-size: 14px;
  letter-spacing: 1px;
  user-select: none;
}

.ai-floating-button:hover {
  background-color: #3e8e41;
  width: 45px;
  box-shadow: 2px 0 12px rgba(0, 0, 0, 0.2);
}
</style> 